//
//  HomePageViewController.m
//  Menu
//
//  Created by YouLu on 15/7/3.
//  Copyright (c) 2015年 lijiangang. All rights reserved.
//

#import "HomePageViewController.h"

@interface HomePageViewController ()

@end

@implementation HomePageViewController

- (void)dealloc
{
    [_cell release];
    [_collectionView release];
    [_homePageModelArray release];
    [_searchLabel release];
    [_navImgView release];
    [_HUD release];
    
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"home_icon_list@3x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(presentLeftMenuViewController:)] autorelease];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    //----------------导航栏添加搜索功能 分类功能-------------    
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"分类" style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonFunction:)] autorelease];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor blackColor];
    
    //-----------------创建数组------------------------------
    self.homePageModelArray = [NSMutableArray array];
    
    //-----------------collectionView-----------------------
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    //设置item大小
    flowLayout.itemSize = CGSizeMake(MyWidth, MyHeight-49-64);
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    //水平方向默认的
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, MyWidth, MyHeight-64-49) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.pagingEnabled = YES;
    [self.collectionView registerClass:[HomePageCollectionViewCell class] forCellWithReuseIdentifier:@"resuse"];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    [_collectionView release];
    [flowLayout release];
//----------------------------------------------------------
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.labelText = @"loading";
    [self.HUD show:YES];
    self.page = 1;
    
    //--------缓存-----------------------------------------
    [[DataHandle shareData] openDataBase];
    [[DataHandle shareData] createHomeCacheTable];
    self.homePageModelArray = [[DataHandle shareData] selectHomeCacheTable];
    
    //-----------------调用AFN请求数据------------------------
    [self loadData];
}

-(void)rightButtonFunction:(UIBarButtonItem *)rightBtnItem
{
    
    SortViewController *sortVC = [[SortViewController alloc] init];
    [self.navigationController pushViewController:sortVC animated:YES];
    [sortVC release];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@"1" forKey:@"number"];
    self.navImgView = [[UIImageView alloc] initWithFrame:CGRectMake(75*WIDTH, 0, 225*WIDTH, 35)];
    self.navImgView.image = [UIImage imageNamed:@"searchField.png"];
    [self.navigationController.navigationBar addSubview:self.navImgView];
    self.navImgView.userInteractionEnabled = YES;
    
//    self.navigationController.navigationBar.translucent = NO;
    
    self.searchLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 225*WIDTH, 35)];
    self.searchLabel.backgroundColor = [UIColor clearColor];
    self.searchLabel.text = @"搜你想吃";
    self.searchLabel.textAlignment = NSTextAlignmentCenter;
    self.searchLabel.textColor = [UIColor lightGrayColor];
    [self.navImgView addSubview:self.searchLabel];
    
    UITapGestureRecognizer *labelTap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTapFunction:)] autorelease];
    [self.searchLabel addGestureRecognizer:labelTap];
    self.searchLabel.userInteractionEnabled = YES;
    [_searchLabel release];
    [_navImgView release];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navImgView removeFromSuperview];
}

//轻拍触发搜索方法-------------------------------------
-(void)labelTapFunction:(UITapGestureRecognizer *)tap
{
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    searchVC.net = self.netOK;
    [self.navigationController pushViewController:searchVC animated:YES];
    [searchVC release];
}

//-----------------AFN------------------------------
-(void)loadData
{
    NSString *str = [NSString stringWithFormat:@"http://121.41.84.91:80/HandheldKitchen/api/more/tblcalendaralertinfo!getHomePage.do?phonetype=2&page=%ld&pageRecord=10&user_id=&is_traditional=0",self.page];
    
    [AFNTool get:str Body:nil HttpResult:JSON success:^(id result) {
        
        if (self.page == 1) {
            
            [self.homePageModelArray removeAllObjects];
            [[DataHandle shareData] dropHomeCacheTable];
        }
        [[DataHandle shareData] createHomeCacheTable];
        NSMutableArray *dataArray = [result objectForKey:@"data"];
        for (NSMutableDictionary *dic in dataArray) {
            HomePageModel *homePageModel = [[HomePageModel alloc] initWithDic:dic];
            
            [self.homePageModelArray addObject:homePageModel];
            [[DataHandle shareData] insertHomeCache:homePageModel];
            [homePageModel release];
        }
        [self.collectionView reloadData];
        [self.HUD hide:YES];
        self.netOK = YES;
    } failure:^(NSError *error) {
        
        [self.HUD hide:YES];
        self.netOK = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"网络错误" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil , nil];
        [alert show];
        [alert release];
        
 
    }];
}
//---------------自定义cell-----------------------------
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.homePageModelArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"resuse" forIndexPath:indexPath];
    self.cell.homePageModel = [self.homePageModelArray objectAtIndex:indexPath.row];
    return self.cell;
    
}
//-----------------点击进入下一页-----------------------------
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (!self.netOK) {
        
        self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.HUD.labelText = @"请求失败";
        [self.HUD show:YES];
        [self.HUD hide:YES afterDelay:0.5];
        return;
    }
    CookingViewController *cookingVC = [[CookingViewController alloc] init];
    HomePageModel *homePageModel = [self.homePageModelArray objectAtIndex:indexPath.row];
    cookingVC.imagePathThumbnails = homePageModel.imagePathThumbnails;
    cookingVC.vegetable_id = homePageModel.vegetable_id;
    cookingVC.foodName = homePageModel.name;
    [self.navigationController pushViewController:cookingVC animated:YES];
    [cookingVC release];
}
//-----------------向左加载-----------------------------
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x > self.page*9*MyWidth) {
        self.page++;
        [self loadData];
        [self.HUD show:YES];
    }
    
    //NSLog(@"开始减速的时候被执行");
}
//-----------------给pageControl传值--------------------------
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger page = (scrollView.contentOffset.x/MyWidth);
    NSInteger pageControl = page%10;
    [self.cell pageControlPage:pageControl];
    //NSLog(@"停止减速的时候被执行");
}
//------------------协议方法push---------------
-(void)pushToCollectController
{
    CollectViewController *collectVC = [[CollectViewController alloc] init];
    [self.navigationController pushViewController:collectVC animated:YES];
    [collectVC release];
}

-(void)pushToEssentialController
{
    EssentialViewController *essentialVC = [[EssentialViewController alloc] init];
    [self.navigationController pushViewController:essentialVC animated:YES];
    [essentialVC release];
}

-(void)pushToRandomController
{
    RandomViewController *randomVC = [[RandomViewController alloc] init];
    [self.navigationController pushViewController:randomVC animated:YES];
    [randomVC release];
}
















- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
